<?php
namespace Home\Controller;

use Model\UserModel;
use Think\Controller;

class UsersController extends BaseController
{

    public function __construct()
    {
        parent::__construct();

    }

    public function information()
    {

        // print_r($_REQUEST);
        $code = I("get.code");
        $state = I("get.state");
        if (empty($code) && empty($state)) {
            $this->error("非法访问", "/");
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C("APP_ID") . "&secret=" . C('App_SECRET') . "&code=" . $code . "&grant_type=authorization_code";
        $res =  file_get_contents($url);
        $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量

        $accessToken = $result['access_token'];
        $openId = $result['openid'];

        $userMessageUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$accessToken."&openid=".$openId."";
        $userMessage = file_get_contents($userMessageUrl);
        $userMessage = json_decode($userMessage,true);

        if($userMessage['errcode'] == "41001"){
            $this->error("授权失败");
        }
        $this->assign("userMessage",$userMessage);
        $userModel = new UserModel();
        $findUser = $userModel->where("`username` = '{$userMessage['unionid']}'")->find();
        if(!empty($findUser)){
            cookie("id",$findUser['id']);
            $this->success('登录成功','/');
        }

        $this->display();
    }
    public function register(){
        $userModel = new UserModel();
        $data= $userModel->create();
        $code =I("post.code");
        if($code !="123456"){
            $this->error("验证码不正确");
        }
        if(empty($data['studentName'])){
            $this->error("学生姓名不可为空");
        }
        if(empty($data['school'])){
            $this->error("学校不可为空");
        }
        if(empty($data['classes'])){
            $this->error("班级不可为空");
        }
        if(empty($data['phone'])){
            $this->error("手机不可为空");
        }
        $findByPhone = $userModel->where("`phone` = '{$data['phone']}'")->find();
        if(!empty($findByPhone)){
            $this->error("手机号已被占用");
        }
        $data['username'] = $data['unionId'];
        $addUserId = $userModel->add($data);
        if($addUserId){
            cookie("id",$addUserId);
            $this->success('登录成功','/');
        }
    }
    public function LoginByPhone(){
        $phone = I("post.phone");
        $code = I("post.code");
        if($code !="123456"){
            $this->error("验证码不正确");
        }
        if(empty($phone)){
            $this->error("手机号不可为空");
        }
        $userModel = new UserModel();
        $findUser = $userModel->where("`phone` = '{$phone}'")->find();
        if(!empty($findUser)){
            cookie("id",$findUser['id']);
            $this->success('登录成功','/');
        }
    }

    public function loginout(){
        cookie("id",null);
        $this->success('退出成功','/');
    }
}